# -*- coding: utf-8 -*-

import json
import logging
from collections import defaultdict

from game.chessmsg import ChessMsg
from game.chessmsg import Role
from game.chessmsg import Side
from net.msg import EventType
from net.netserv import Adapter
from net.netserv import NetServer

logging.getLogger().setLevel(logging.INFO)


class ChessServAdapter(Adapter):

    def __init__(self):
        self.handler_table = defaultdict(lambda: [])
        self.chess_table = defaultdict(lambda: [])

    def handle_init(self, handler, ctx=None):
        logging.info(ctx)
        chess_msg = ChessMsg.json2obj(ctx.data)
        if not chess_msg:
            return
        if len(self.handler_table[chess_msg.grp]) == 0:
            chess_msg.side = Side.WHITE
            chess_msg.role = Role.PARTICIPANT
        elif len(self.handler_table[chess_msg.grp]) == 1:
            chess_msg.side = Side.BLACK
            chess_msg.role = Role.PARTICIPANT
        else:
            chess_msg.role = Role.OBSERVER
        handler.grp_id = chess_msg.grp
        self.handler_table[handler.grp_id].append(handler)
        handler.send_event(cmd=EventType.INIT, data=chess_msg.to_json())

    def handle_data(self, handler, ctx):
        logging.info(ctx)
        chess_msg = ChessMsg.json2obj(ctx.data)
        if not chess_msg:
            return
        if chess_msg.role != Role.PARTICIPANT:
            return
        self.chess_table[handler.grp_id].append(chess_msg)
        for _handler in self.handler_table.get(handler.grp_id):
            _handler.send_event(cmd=EventType.DATA, data=ctx.data)

    def handle_create_grp(self, handler, ctx):
        logging.info(ctx)
        handler.send_event(cmd=EventType.CREATE_GRP, data='create group TODO')

    def handle_join_grp(self, handler, ctx):
        logging.info(ctx)
        handler.send_event(cmd=EventType.JOIN_GRP, data='join TODO')

    def handle_sync_data(self, handler, ctx):
        logging.info(ctx)
        chess_lst = json.dumps(self.chess_table[handler.grp_id])
        logging.info(chess_lst)
        handler.send_event(cmd=EventType.SYNC_DATA, data=chess_lst)

    def handle_ready(self, handler, ctx=None):
        logging.info(ctx)
        handler.send_event(cmd=EventType.READY, data='ready TODO')

    def handle_pause(self, handler, ctx=None):
        logging.info(ctx)
        handler.send_event(cmd=EventType.PAUSE, data='pause TODO')

    def handle_resume(self, handler, ctx=None):
        logging.info(ctx)
        handler.send_event(cmd=EventType.RESUME, data='resume TODO')

    def handle_quit(self, handler, ctx=None):
        super(ChessServAdapter, self).handle_quit(handler=handler, ctx=ctx)
        self.handler_table[handler.grp_id].remove(handler)
        logging.info('remains: %s', self.handler_table)


if __name__ == '__main__':
    NetServer(adapter=ChessServAdapter()).start()
